package de.breitbeil.jbooking.ui.form;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Date;

import javax.swing.JComponent;
import javax.swing.JTextField;

import org.springframework.richclient.form.AbstractForm;
import org.springframework.richclient.form.binding.BindingFactory;
import org.springframework.richclient.form.builder.TableFormBuilder;

import de.breitbeil.jbooking.domain.Booking;

public class BookingForm extends AbstractForm {

    public BookingForm(Booking booking) {
        super(booking);
        setId("bookingForm");
        
        DateChangeListener listener = new DateChangeListener();
        getValueModel("from").addValueChangeListener(listener);
        getValueModel("to").addValueChangeListener(listener);
    }

    @Override
    protected JComponent createFormControl() {
        BindingFactory bindingFactory = getBindingFactory();
        TableFormBuilder formBuilder = new TableFormBuilder(bindingFactory);
        formBuilder.setLabelAttributes("colGrId=label colSpec=right:pref");
        
        formBuilder.addSeparator(getMessage(getId()) + ".bookingSeparator.label");
        formBuilder.row();
        formBuilder.add("person");
        formBuilder.row();
        formBuilder.add("bookingType");
        formBuilder.row();
        formBuilder.add("from", "align=left");
        JTextField numDaysField = (JTextField) formBuilder.add("numDays", "align=left")[1];
        numDaysField.setEditable(false);
        formBuilder.row();
        formBuilder.add("to", "align=left");
        formBuilder.row();
        formBuilder.add("bookingDate", "align=left");
        formBuilder.row();
        formBuilder.add("prepayment", "align=left");
        formBuilder.row();
        formBuilder.add("price", "align=left");
        formBuilder.row();
        
        formBuilder.addSeparator(getMessage(getId()) + ".personSeparator.label");
        formBuilder.row();
        setColumns(formBuilder.add("numberAdults", "align=left")[1]);
        formBuilder.row();
        setColumns(formBuilder.add("numberChildren", "align=left")[1]);
        formBuilder.row();
        setColumns(formBuilder.add("numberDogs", "align=left")[1]);
        formBuilder.row();
        
        formBuilder.addSeparator(getMessage(getId()) + ".commentSeparator.label");
        formBuilder.row();
        formBuilder.addTextArea("comment");
        
        return formBuilder.getForm();
    }

    private void setColumns(JComponent field) {
        JTextField textField = (JTextField) field;
        textField.setColumns(2);
    }
    
    protected class DateChangeListener implements PropertyChangeListener {
		public void propertyChange(PropertyChangeEvent evt) {
			Date from = (Date) getValueModel("from").getValue();
			Date to = (Date) getValueModel("to").getValue();
			
			int days = Booking.getNumDays(from, to);
			getValueModel("numDays").setValue(days);
		}
    }
    
}
